package com.think.common.security.config;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.think.common.core.utils.DateUtils;
import com.think.common.core.utils.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;

public class TimestampDeserializer extends JsonDeserializer<Timestamp> {

    @Override
    public Timestamp deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
        String source = p.getValueAsString();
        if (source == null) {
            return null;
        }
        Timestamp timestamp = null;
        //判断当前日期格式 ,前端传递 yyyy-MM-dd,服务端传递时间戳
        if (source.length() == 10) {
            Date date = DateUtils.parseDate(source);
            timestamp = new Timestamp(date.getTime());
        } else if (StringUtils.isNumeric(source)) {
            timestamp = new Timestamp(Long.parseLong(source));
        } else {
            throw new IllegalArgumentException("Invalid date format : " + source);
        }
        return timestamp;
    }
}
